from flask import Flask
from flask_caching import Cache
import os

class Context:
    _instance = None  # 单例实例
    __contextDict = {}  # 私有容器

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(Context, cls).__new__(cls)
        return cls._instance

    def __init__(self):
        if not Context.__contextDict:  # 只在首次初始化时创建
            app = self.__initFlaskApp()
            Context.__contextDict["app"] = app
            cache = self.__initCache(app=app)
            Context.__contextDict["cache"] = cache

    def __initFlaskApp(self):
        app = Flask(__name__)
        app.config.from_mapping(
            DEBUG=os.getenv("FLASK_DEBUG", False),
            SECRET_KEY=os.getenv("FLASK_SECRET_KEY", "dev")
        )
        return app

    def __initCache(self, app):
        # config = {
        #     'CACHE_TYPE': "redis",
        #     'CACHE_REDIS_URL': os.getenv("REDIS_URL", "redis://localhost:6379/0"),
        #     'CACHE_KEY_PREFIX': "sjzh:",
        #     "CACHE_DEFAULT_TIMEOUT": int(os.getenv("CACHE_TIMEOUT", 3000))
        # }
        config={
            'CACHE_TYPE': "redis",
            'CACHE_REDIS_URL': "redis://192.168.154.128:6380/1",
            'CACHE_KEY_PREFIX': "sjzh:",
            "CACHE_DEFAULT_TIMEOUT": 3000
        }
        try:
            cache=Cache(app=app,config=config) 
            # 测试连接（可选）
            with app.app_context():
                cache.set("test_key", "test_value")
                assert cache.get("test_key") == "test_value"
            return cache
        except Exception as e:
            raise RuntimeError(f"Failed to initialize cache: {str(e)}")

    @classmethod
    def getApp(cls):
        return cls.__contextDict.get("app")

    @classmethod
    def getCache(cls):
        return cls.__contextDict.get("cache")

# 使用示例
context = Context()
app:Flask = context.getApp()
cache:Cache = context.getCache()